<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="utf-8">
    <title>浏览页面</title>
    <link rel="stylesheet" href="/app/admin/component/pear/css/pear.css" />
    <link rel="stylesheet" href="/app/admin/admin/css/reset.css" />
    <style>
        .layui-table-view {
            overflow-x: auto !important;
        }

        .layui-table-header th,
        .layui-table-body td {
            /* white-space: normal !important; */
            min-width: 140px !important;
            max-width: 400px !important;
            word-break: break-all !important;
            overflow: visible !important;
            text-overflow: initial !important;
        }

        .layui-table-cell {
            /* white-space: normal !important; */
            word-break: break-all !important;
            overflow: visible !important;
            text-overflow: initial !important;
            height: auto !important;
            line-height: 1.5 !important;
            display: block !important;
        }

        .layui-table-header th {
            background: #f8f8f8;
            font-weight: bold;
        }

        .layui-table-box {
            overflow-x: auto !important;
        }

        .layui-table-main {
            overflow-x: auto !important;
        }

        .layui-card-body>div[style*='overflow-x:auto'] {
            overflow-x: auto !important;
        }
    </style>
</head>

<body class="pear-container">

    <!-- 顶部查询表单 -->
    <div class="layui-card">
        <div class="layui-card-body">
            <form class="layui-form top-search-from">

                <div class="layui-form-item">
                    <label class="layui-form-label">创建时间</label>
                    <div class="layui-input-block">
                        <div class="layui-input-block" id="created_at">
                            <input type="text" autocomplete="off" name="created_at[]" id="created_at-date-start"
                                class="layui-input inline-block" placeholder="开始时间">
                            -
                            <input type="text" autocomplete="off" name="created_at[]" id="created_at-date-end"
                                class="layui-input inline-block" placeholder="结束时间">
                        </div>
                    </div>
                </div>

                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">设备ID</label>
                    <div class="layui-input-block">
                        <select name="device_id" lay-search>
                            <option value="">请选择</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">网关ID</label>
                    <div class="layui-input-block">
                        <input type="text" name="gateway_id" placeholder="请输入网关ID" autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label"></label>
                    <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="table-query">
                        <i class="layui-icon layui-icon-search"></i>查询
                    </button>
                    <button type="reset" class="pear-btn pear-btn-md" lay-submit lay-filter="table-reset">
                        <i class="layui-icon layui-icon-refresh"></i>重置
                    </button>
                    <button class="pear-btn pear-btn-md pear-btn-primary" id="export-btn" type="button">
                        <i class="layui-icon layui-icon-export"></i>导出
                    </button>
                </div>
                <div class="toggle-btn">
                    <a class="layui-hide">展开<i class="layui-icon layui-icon-down"></i></a>
                    <a class="layui-hide">收起<i class="layui-icon layui-icon-up"></i></a>
                </div>
            </form>
        </div>
    </div>

    <!-- 数据表格 -->
    <div class="layui-card">
        <div class="layui-card-body">
            <div style="overflow-x:auto;">
                <table id="data-table" lay-filter="data-table"></table>
            </div>
        </div>
    </div>

    <!-- 表格顶部工具栏 -->
    <!-- <script type="text/html" id="table-toolbar">
            <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="add" permission="app.admin.qualityinfo.insert">
                <i class="layui-icon layui-icon-add-1"></i>新增
            </button>
            <button class="pear-btn pear-btn-danger pear-btn-md" lay-event="batchRemove" permission="app.admin.qualityinfo.delete">
                <i class="layui-icon layui-icon-delete"></i>删除
            </button>
        </script> -->

    <!-- 表格行工具栏 -->
    <!-- <script type="text/html" id="table-bar">
            <button class="pear-btn pear-btn-xs tool-btn" lay-event="edit" permission="app.admin.qualityinfo.update">编辑</button>
            <button class="pear-btn pear-btn-xs tool-btn" lay-event="remove" permission="app.admin.qualityinfo.delete">删除</button>
        </script> -->

    <script src="/app/admin/component/layui/layui.js?v=2.8.12"></script>
    <script src="/app/admin/component/pear/pear.js"></script>
    <script src="/app/admin/admin/js/permission.js"></script>
    <script src="/app/admin/admin/js/common.js"></script>

    <script>

        // 相关常量
        const PRIMARY_KEY = "id";
        const SELECT_API = "/app/admin/quality-info/select";
        const UPDATE_API = "/app/admin/quality-info/update";
        const DELETE_API = "/app/admin/quality-info/delete";
        const INSERT_URL = "/app/admin/quality-info/insert";
        const UPDATE_URL = "/app/admin/quality-info/update";

        // 字段 创建时间 created_at
        layui.use(["laydate"], function () {
            layui.laydate.render({
                elem: "#created_at",
                range: ["#created_at-date-start", "#created_at-date-end"],
                type: "datetime",
            });
        })

        // 表格渲染
        layui.use(["table", "form", "common", "popup", "util"], function () {
            let table = layui.table;
            let form = layui.form;
            let $ = layui.$;
            let common = layui.common;
            let util = layui.util;

            // 获取设备列表数据
            $.ajax({
                url: "/app/admin/device/select?format=select",
                dataType: "json",
                success: function (res) {
                    if (res.code === 0 && res.data) {
                        let deviceSelect = $('select[name="device_id"]');
                        res.data.forEach(function(item) {
                            deviceSelect.append(`<option value="${item.value}">${item.name}</option>`);
                        });
                        form.render('select'); // 重新渲染select
                    }
                }
            });

            // 表头参数
            let cols = [

                // {
                //     title: "id", align: "center",
                //     field: "id",
                // },
                {
                    title: "采集时间", align: "center",
                    field: "created_at",	
                    sort: true,
                },
                { title: "GATEID", field: "device.gateway_id", align: "center",templet: function(d){ return d.device.gateway_id} },
                { title: "设备ID", field: "device.sn", align: "center",templet: function(d){ return d.device.sn}  },
                { title: "PH", field: "ph", align: "center" },
                { title: "TDS(产水TDS)", field: "tds", align: "center" },
                { title: "CL(产水余氯)", field: "cl", align: "center" },
                { title: "WATER(产水量)", field: "water", align: "center"},
                { title: "FILTER(制水次数)", field: "filter", align: "center"},
                { title: "STATUS(状态)", field: "status", align: "center"},
                { title: "AUTO(运行模式)", field: "auto", align: "center"},
                { title: "ALARM(报警代码)", field: "alarm", align: "center"},
                // {
                // 	title: "设备名称",align: "center",
                // 	field: "device_id",
                // 	templet: function (d) {
                // 		let field = "device_id";
                // 		if (typeof d[field] == "undefined") return "";
                // 		let items = [];
                // 		layui.each((d[field] + "").split(","), function (k , v) {
                // 			items.push(apiResults[field][v] || v);
                // 		});
                // 		return util.escape(items.join(","));
                // 	}
                // },
                {
                    title: "进水压力", align: "center",
                    field: "inlet_pressure",
                }, {
                    title: "进水流量", align: "center",
                    field: "inlet_flow",
                }, {
                    title: "进水TDS", align: "center",
                    field: "inlet_tds",
                }, {
                    title: "产水压力", align: "center",
                    field: "outlet_pressure",
                }, {
                    title: "产水流量", align: "center",
                    field: "outlet_flow",
                }, 
                // {
                //     title: "产水余氯", align: "center",
                //     field: "outlet_chlorine",
                // },
                 {
                    title: "产水温度", align: "center",
                    field: "outlet_temp",
                }, {
                    title: "总进水量", align: "center",
                    field: "total_inlet",
                },
                // {
                //     title: "总产水量", align: "center",
                //     field: "total_outlet",
                // },
                 {
                    title: "水箱液位", align: "center",
                    field: "tank_level",
                }, {
                    title: "反洗时间", align: "center",
                    field: "backwash_time",
                }, {
                    title: "反冲时间", align: "center",
                    field: "backflush_time",
                }, {
                    title: "排空时间", align: "center",
                    field: "drain_time",
                }, {
                    title: "正冲时间", align: "center",
                    field: "forward_flush_time",
                }, {
                    title: "制水排放时间", align: "center",
                    field: "water_production_drain_time",
                }, {
                    title: "过滤制水时间", align: "center",
                    field: "filter_water_time",
                }, {
                    title: "浓水阀开度", align: "center",
                    field: "concentrate_valve_opening",
                }, {
                    title: "水箱下限控制点", align: "center",
                    field: "tank_lower_limit",
                }, {
                    title: "水箱上限控制点", align: "center",
                    field: "tank_upper_limit",
                }, {
                    title: "手/自动状态", align: "center",
                    field: "manual_auto_status",
                }, {
                    title: "自动状态", align: "center",
                    field: "auto_status",
                }, {
                    title: "手动状态", align: "center",
                    field: "manual_status",
                }, {
                    title: "4G信号IP", align: "center",
                    field: "cellular_ip",
                }, {
                    title: "无线WIFI地址", align: "center",
                    field: "wifi_address",
                }, {
                    title: "无线WIFI名", align: "center",
                    field: "wifi_name",
                }, {
                    title: "有线IP地址", align: "center",
                    field: "wired_ip_address",
                }, {
                    title: "漏水状态", align: "center",
                    field: "leak_status",
                }, {
                    title: "水箱上限报警点", align: "center",
                    field: "tank_upper_alarm",
                }, {
                    title: "水箱下限报警点", align: "center",
                    field: "tank_lower_alarm",
                }, {
                    title: "TDS报警点", align: "center",
                    field: "tds_alarm",
                }, {
                    title: "产水水温报警点", align: "center",
                    field: "outlet_temp_alarm",
                }, {
                    title: "产水率报警基准", align: "center",
                    field: "outlet_rate_alarm_base",
                }, {
                    title: "产水率报警偏差", align: "center",
                    field: "outlet_rate_alarm_deviation",
                }
                // ,{
                // 	title: "操作",
                // 	toolbar: "#table-bar",
                // 	align: "center",
                // 	fixed: "right",
                // 	width: 120,
                // }
            ];

            // 记录当前where条件
            let currentWhere = {};
            form.on("submit(table-query)", function (data) {
                currentWhere = data.field;
                // 设置url并重新加载表格
                table.reload("data-table", {
                    url: SELECT_API,
                    page: { curr: 1 },
                    where: data.field
                });
                return false;
            });
            // 兼容重置按钮
            form.on("submit(table-reset)", function (data) {
                currentWhere = {};
                // 重置后清空表格数据
                table.reload("data-table", {
                    url: "",
                    where: [],
                    data: []
                });
            });
            // 让自带导出按钮携带where参数
            table.render({
                elem: "#data-table",
                page: true,
                cols: [cols],
                skin: "line",
                size: "lg",
                defaultToolbar: ["filter", "print", "exports"],
                where: currentWhere,
                data: [], // 默认不查询数据
                parseData: function(res){
                    // 记录最新where参数，供导出按钮使用
                    this.where = currentWhere;
                    return res;
                }
            });

            // 获取表格中下拉或树形组件数据
            // 已通过上面的设备列表获取逻辑处理，此处删除重复代码

            // 编辑或删除行事件
            table.on("tool(data-table)", function (obj) {
                if (obj.event === "remove") {
                    remove(obj);
                } else if (obj.event === "edit") {
                    edit(obj);
                }
            });

            // 表格顶部工具栏事件
            table.on("toolbar(data-table)", function (obj) {
                if (obj.event === "add") {
                    add();
                } else if (obj.event === "refresh") {
                    refreshTable();
                } else if (obj.event === "batchRemove") {
                    batchRemove(obj);
                }
            });

            // 表格排序事件
            table.on("sort(data-table)", function (obj) {
                table.reload("data-table", {
                    url: SELECT_API,
                    initSort: obj,
                    scrollPos: "fixed",
                    where: {
                        ...currentWhere,  // 保留当前筛选条件
                        field: obj.field,
                        order: obj.type
                    }
                });
            });

            // 表格新增数据
            let add = function () {
                layer.open({
                    type: 2,
                    title: "新增",
                    shade: 0.1,
                    maxmin: true,
                    area: [common.isModile() ? "100%" : "500px", common.isModile() ? "100%" : "450px"],
                    content: INSERT_URL
                });
            }

            // 表格编辑数据
            let edit = function (obj) {
                let value = obj.data[PRIMARY_KEY];
                layer.open({
                    type: 2,
                    title: "修改",
                    shade: 0.1,
                    maxmin: true,
                    area: [common.isModile() ? "100%" : "500px", common.isModile() ? "100%" : "450px"],
                    content: UPDATE_URL + "?" + PRIMARY_KEY + "=" + value
                });
            }

            // 删除一行
            let remove = function (obj) {
                return doRemove(obj.data[PRIMARY_KEY]);
            }

            // 删除多行
            let batchRemove = function (obj) {
                let checkIds = common.checkField(obj, PRIMARY_KEY);
                if (checkIds === "") {
                    layui.popup.warning("未选中数据");
                    return false;
                }
                doRemove(checkIds.split(","));
            }

            // 执行删除
            let doRemove = function (ids) {
                let data = {};
                data[PRIMARY_KEY] = ids;
                layer.confirm("确定删除?", {
                    icon: 3,
                    title: "提示"
                }, function (index) {
                    layer.close(index);
                    let loading = layer.load();
                    $.ajax({
                        url: DELETE_API,
                        data: data,
                        dataType: "json",
                        type: "post",
                        success: function (res) {
                            layer.close(loading);
                            if (res.code) {
                                return layui.popup.failure(res.msg);
                            }
                            return layui.popup.success("操作成功", refreshTable);
                        }
                    })
                });
            }

            // 刷新表格数据
            window.refreshTable = function () {
                // 只有在有筛选条件时才刷新数据
                if (Object.keys(currentWhere).length > 0) {
                    table.reload("data-table", {
                        url: SELECT_API,
                        where: currentWhere,
                        scrollPos: "fixed",
                        done: function (res, curr) {
                            if (curr > 1 && res.data && !res.data.length) {
                                curr = curr - 1;
                                table.reload("data-table", {
                                    url: SELECT_API,
                                    where: currentWhere,
                                    page: {
                                        curr: curr
                                    },
                                })
                            }
                        }
                    });
                }
            }

            document.getElementById('export-btn').onclick = function () {
                // 获取当前筛选条件
                let where = {};
                let start = document.getElementById('created_at-date-start').value;
                let end = document.getElementById('created_at-date-end').value;
                if (start) where['created_at[0]'] = start;
                if (end) where['created_at[1]'] = end;
                let device_id = document.querySelector('select[name="device_id"]').value;
                let gateway_id = document.querySelector('input[name="gateway_id"]').value;
                if (device_id) where['device_id'] = device_id;
                if (gateway_id) where['gateway_id'] = gateway_id;
                layui.$.ajax({
                    url: SELECT_API,
                    data: Object.assign({}, where, { limit: 10000, page: 1 }), // 限制最多1w条
                    success: function (res) {
                        if (res.code === 0 && res.data) {
                            if (res.count > 10000) {
                                layer.msg('导出数据不能超过1万条，请缩小筛选范围');
                                return;
                            }
                            // 生成表头和字段数组
                            let headers = cols.map(col => col.title);
                            let fields = cols.map(col => col.field);
                            // 格式化采集时间
                            function formatTime(str) {
                                if (!str) return '';
                                let d = new Date(str.replace(/-/g, '/'));
                                const week = ['日','一','二','三','四','五','六'];
                                return `周${week[d.getDay()]} ${d.getMonth()+1}月 ${d.getDate()} ${d.toTimeString().slice(0,8)} ${d.getFullYear()}`;
                            }
                            let exportData = res.data.map(row => fields.map(f => {
                                if (f === 'created_at') {
                                    return formatTime(row[f]);
                                }
                                if (f && f.indexOf('.') > -1) {
                                    let parts = f.split('.');
                                    let val = row;
                                    for (let p of parts) {
                                        val = val ? val[p] : '';
                                    }
                                    return val;
                                }
                                return row[f];
                            }));
                            exportData.unshift(headers);
                            layui.table.exportFile(headers, exportData.slice(1), 'xls');
                        } else {
                            layer.msg('暂无可导出数据');
                        }
                    },
                    error: function () {
                        layer.msg('导出失败');
                    }
                });
            };
        })

    </script>
</body>

</html>